package tool;

import java.sql.Connection;
import java.util.Calendar;

import org.apache.log4j.Logger;

import lib.Db;
import lib.Global;
import lib.KeyMa;
import lib.MyLog;
import lib.TableStatus;

import reference.MyStatus;
import weibo4j.Timeline;
import weibo4j.Weibo;
import weibo4j.model.Paging;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.WeiboException;

public class MStatus {
	/**
	 * 
	 * @param uid
	 * @return StatusWapper
	 */
	public static StatusWapper UpdateStatusByUserId(String uid){
		Logger logger = MyLog.getLogger(MStatus.class.getName());
		
		StatusWapper myStatuslist = new StatusWapper();
		int pagenum = 1;
		
		Connection con = Db.connect();
		Long timeOfLatestStatus = TableStatus.getTimeOfLatestStatus(uid, con);

		while(getNextPage){

			Paging page = new Paging(pagenum, Global.MAX_STATUS);
			Integer base = new Integer(0);
			Integer feature = new Integer(0);
			
			StatusWapper receive = getPage(uid, page, base, feature);
			if(receive != null){
				for(Status aStatus : receive.getStatuses()){
					if(shouldAdd(aStatus, timeOfLatestStatus)){
						myStatuslist.add(translate(aStatus));
					}
				}
				if(pagenum*Global.MAX_STATUS >= receive.getTotalNumber()){
					getNextPage = false;
					messageStopGet = "already get all status";
				}
			}
			++pagenum;
		}
		
		getNextPage = true;
		errorPage = 0;
		logger.info("stop get status: "+messageStopGet);
		return myStatuslist;
	}
	
	private static StatusWapper getPage(String uid, Paging page, Integer base, Integer feature){
		Logger logger = MyLog.getLogger(MStatus.class.getName());

		Weibo weibo = new Weibo();
		KeyMa aToken = new KeyMa();
		int tryTime = 0;
	
		while(tryTime != Global.TRYTIME_STATUS){
			try {
				weibo.setToken(aToken.getToken());
				Timeline tm = new Timeline();
				
				StatusWapper receive = tm.getUserTimelineByUid(uid, page, base, feature);
				if(receive == null ){
					logger.warn(uid + ": get "+page.getPage()+"st page status return null, try again.");
					tryTime++;
				}else if(receive.getStatuses().size() == 0 && receive.getTotalNumber() != 0){
					logger.warn(uid + ": get "+page.getPage()+"st page status return 0, try again.");
					tryTime++;
				}else if(receive.getStatuses().size() == 0 && receive.getTotalNumber() == 0){
					logger.info(uid+" get status, do not have any status");
					return receive;
				}else{
					logger.info(uid+" get status, "+ page.getPage()+"st page get.");
					return receive;
				}
			} catch (WeiboException e) {
				logger.warn(uid + ": get "+page.getPage()+"st page status failed, try again.");
				logger.warn(e.getMessage());
				tryTime++;
			}
		}
		++errorPage;
		if(errorPage == 3){
			getNextPage = false;
			messageStopGet = "get too many error pages";
		}
		logger.error(uid+ ": get "+page.getPage()+"st page status return empty, skip it.");
		return null;	
	}

	private static Status translate(Status aStatus){
		MyStatus mystatus = new MyStatus(aStatus);
		if(aStatus.getRetweetedStatus()==null){
			mystatus.setFid(null);
			mystatus.setFlag(0);
		}else{
			if(aStatus.getRetweetedStatus().getUser() == null)
				mystatus.setFid("error");
			else
				mystatus.setFid(aStatus.getRetweetedStatus().getUser().getId());
			mystatus.setFlag(1);
		}
		return mystatus;
	}
	
	private static boolean shouldAdd(Status aStatus, Long latest){
		Calendar timeLine = Calendar.getInstance();
		timeLine.add(Calendar.MONTH, -1*Global.MONTH_STATUS);
		
		Calendar latestTime = Calendar.getInstance();
		latestTime.setTimeInMillis(latest);
		
		Calendar timeStatus = Calendar.getInstance();
		timeStatus.setTime(aStatus.getCreatedAt());
		
		if(timeStatus.after(timeLine) && timeStatus.after(latestTime)){
			return true;
		}else{
			getNextPage = false;
			messageStopGet = "already get latest status";
			return false;
		}
	}
	
/*	
	public static StatusWapper UpdateStatusById(String uid) throws InterruptedException, IOException{
		Weibo weibo = new Weibo();
		TokenMa aToken = new TokenMa();
		StatusWapper receive;
		int flagError = 0;
		do{
			try {	
				weibo.setToken(aToken.getToken());
				Timeline tm = new Timeline();
				
				Paging page = new Paging(1, 100);
				Integer base = new Integer(0);
				Integer feature = new Integer(0);
				receive = tm.getUserTimelineByUid(uid, page, base, feature);
				if(receive.getStatuses().size() != 0 && receive != null){
					StatusWapper myStatuslist = new StatusWapper();
					for(Status astatus : receive.getStatuses()){
						myStatuslist.add(translate(astatus));
					}
					return myStatuslist;
				}else{
					String des = "update status return empty, try again.";
					RecordError.WriteError(uid, des);
					flagError++;
				}					
			}catch (WeiboException e) {
				e.printStackTrace();
				return null;
			}
		}while(flagError < TRY_MAX);
		
		return null;
	}
*/	
	static boolean getNextPage = true;
	static int errorPage = 0;
	static String messageStopGet = null;
}
